package com.mbc.web.common.client.ui;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.mbc.common.data.CurrencyReferenceData;
import com.mbc.web.common.client.ClientSingleton;
import com.mbc.web.common.client.CommonControllerMgr;
import com.mbc.web.common.client.CommonMessage;
import com.mbc.web.common.client.ViewUtils;
import com.google.gwt.uibinder.client.UiField;
import com.mbc.web.common.client.ui.control.MListBox;
import com.mbc.web.common.client.ui.control.MButton;
import com.mbc.web.common.shared.HttpStatus;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;

public class FrmCurrencyReport extends Composite {

	private static FrmCurrencyReportUiBinder uiBinder = GWT
			.create(FrmCurrencyReportUiBinder.class);
	@UiField MListBox listFrom;
	@UiField MListBox listTo;
	@UiField MButton btnView;
	
	interface FrmCurrencyReportUiBinder extends
			UiBinder<Widget, FrmCurrencyReport> {
	}

	public FrmCurrencyReport() {
		initWidget(uiBinder.createAndBindUi(this));
		inititalize();
	}

	private void inititalize(){
		CommonControllerMgr.getAllCurrency(getAllCurrencyCallback());
	}
	
	private AsyncCallback<List<CurrencyReferenceData>> getAllCurrencyCallback(){
		return new AsyncCallback<List<CurrencyReferenceData>>() {
			
			@Override
			public void onSuccess(List<CurrencyReferenceData> result) {
				for (CurrencyReferenceData l_curRef : result) {
					listFrom.addItem(l_curRef.getValue(), String.valueOf(l_curRef.getKey()));
					listTo.addItem(l_curRef.getValue(), String.valueOf(l_curRef.getKey()));
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		};
	}
	
	@UiHandler("btnView")
	void onBtnViewClick(ClickEvent event) {
		ViewUtils.closeMessageBox();
		ViewUtils.startAjaxLoader(CommonMessage.loading_message);
		CommonControllerMgr.viewCurrencyReport(listFrom.getItemText(listFrom.getSelectedIndex()), listTo.getItemText(listTo.getSelectedIndex()), viewCurrencyReportCallback());
	}
	
	private AsyncCallback<Integer> viewCurrencyReportCallback(){
		return new AsyncCallback<Integer>() {
			
			@Override
			public void onSuccess(Integer result) {
				ViewUtils.stopAjaxLoader();
				if(result == HttpStatus.OK){
					ClientSingleton.viewReport("Currency Report");
				} else if(result == HttpStatus.NOT_FOUND){
					ViewUtils.showErrorMessage("No records.");
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		};
	}
}
